package com.iqiyi.pps.epg.core.rpc.reord;

import com.alibaba.fastjson.JSONObject;
import com.iqiyi.pps.epg.api.model.web.query.TFilter;
import com.iqiyi.pps.epg.api.model.web.query.TPage;
import com.iqiyi.pps.epg.api.model.web.query.TResponse;
import com.iqiyi.pps.epg.api.model.web.record.*;
import com.iqiyi.pps.epg.api.server.web.record.RecordWebService;
import com.iqiyi.pps.epg.core.model.record.*;
import com.iqiyi.pps.epg.core.service.record.IRecordAsyncService;
import com.iqiyi.pps.epg.core.service.record.IRecordService;
import com.iqiyi.pps.epg.core.service.record.RecordColService;
import com.iqiyi.pps.epg.core.utils.ApiRecordNotifyUtil;
import com.iqiyi.pps.epg.core.utils.Constants;
import com.iqiyi.pps.epg.core.utils.DateTimeUtil;
import com.iqiyi.pps.epg.core.utils.WriteSystemLogUtil;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Timestamp;
import java.util.List;

/**
 * Created by karkarrotxu on 2018/4/11.
 */
public class RecordWebServiceImpl implements RecordWebService.Iface {
    private static Logger logger = LoggerFactory.getLogger(RecordWebServiceImpl.class);

    private IRecordService getRecordService() {
        return WriteSystemLogUtil.getInstance().getRecordService();
    }

    private RecordColService getRecordColService() {
        return WriteSystemLogUtil.getInstance().getRecordColService();
    }

    private IRecordAsyncService getRecordAsyncService() {
        return WriteSystemLogUtil.getInstance().getRecordAsyncService();
    }

    @Override
    public TResponse addRecordPlan(TRecordPlan entity) {
        TResponse tResponse = new TResponse();
        tResponse.setCode(Constants.CODE_ERROR);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("retValue", 0);
        try {
            RecordPlan recordPlan = new RecordPlan();
            modifyRecordPlanCommon(entity, recordPlan);
            recordPlan.setOpUser(entity.getOpUser());
            recordPlan.setPlanType(entity.getPlanType());
            recordPlan.setCreateTime(new Timestamp(System.currentTimeMillis()));
            long regId = getRecordService().saveRecordPlan(recordPlan);
            tResponse.setCode(Constants.CODE_SUC);
            jsonObject.put("retValue", regId);
            if (regId > 0) {
                if (recordPlan.getEnable() == 1) {
                    updateRecordTaskRule(recordPlan);
                    getRecordAsyncService().changeRecordTaskRule(recordPlan.getId(), RecordTaskRule.STATUS_USE);
                }
            }
        } catch (Exception e) {
            logger.error("ERROR", e);
        }
        tResponse.setJsonData(jsonObject.toJSONString());
        return tResponse;
    }

    private void addRecordTaskRule(RecordPlan recordPlan) {
        RecordTaskRule rule = new RecordTaskRule();
        rule.setPlanId(recordPlan.getId());
        try {
            if (recordPlan.getPlanType() == RecordPlan.TYPE_CYCLE_TIME) {
                rule.setStartTime(new Timestamp(DateTimeUtil.parseLongFormat(recordPlan.getStartDate() + " " + recordPlan.getStartDayTime())));
                rule.setStopTime(new Timestamp(DateTimeUtil.parseLongFormat(recordPlan.getStopDate() + " " + recordPlan.getStopDayTime())));
            } else if (recordPlan.getPlanType() == RecordPlan.TYPE_ALL_TIME) {
                rule.setStartTime(new Timestamp(DateTimeUtil.parseLongFormat(recordPlan.getStartDate() + " 00:00:00")));
                rule.setStopTime(new Timestamp(DateTimeUtil.parseLongFormat(recordPlan.getStopDate() + " 23:59:59")));
            }
            rule.setStatus(RecordTaskRule.STATUS_STOP);
            long currentTime = System.currentTimeMillis();
            rule.setCreateTime(new Timestamp(currentTime));
            rule.setNextExecuteTime(null);
            long regId = getRecordService().saveRecordTaskRule(rule);
            if (regId < 1) {
                logger.error("addRecordTaskRule fail planId{}", recordPlan.getId());
            }
        } catch (Exception e) {
            logger.error("addRecordTaskRule", e);
        }
    }

    private void updateRecordTaskRule(RecordPlan recordPlan) {
        RecordTaskRule rule = getRecordService().getRecordTaskRuleByPlanId(recordPlan.getId());
        if (rule == null) {
            addRecordTaskRule(recordPlan);
        } else {
            if (recordPlan.getPlanType() == RecordPlan.TYPE_CYCLE_TIME) {
                rule.setStartTime(new Timestamp(DateTimeUtil.parseLongFormat(recordPlan.getStartDate() + " " + recordPlan.getStartDayTime())));
                rule.setStopTime(new Timestamp(DateTimeUtil.parseLongFormat(recordPlan.getStopDate() + " " + recordPlan.getStopDayTime())));
            } else if (recordPlan.getPlanType() == RecordPlan.TYPE_ALL_TIME) {
                rule.setStartTime(new Timestamp(DateTimeUtil.parseLongFormat(recordPlan.getStartDate() + " 00:00:00")));
                rule.setStopTime(new Timestamp(DateTimeUtil.parseLongFormat(recordPlan.getStopDate() + " 23:59:59")));
            }
            //long currentTime = System.currentTimeMillis();
            rule.setNextExecuteTime(null);
            getRecordService().editRecordTaskRule(rule);
        }
    }

    @Override
    public TResponse editRecordPlan(TRecordPlan entity) {
        TResponse tResponse = new TResponse();
        tResponse.setCode(Constants.CODE_ERROR);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("retValue", 0);
        if (entity.getId() == 0) {
            jsonObject.put("retValue", 1);
            tResponse.setJsonData(jsonObject.toJSONString());
            return tResponse;
        }
        try {
            RecordPlan recordPlan = getRecordService().getRecordPlanById(entity.getId());

            if (recordPlan == null) {
                jsonObject.put("retValue", -1);
            } else {
                //boolean changeEnable = recordPlan.getEnable() != entity.getEnable();
                int oldEnable = recordPlan.getEnable();
                int newEnable = entity.getEnable();
                if (oldEnable == RecordTaskRule.STATUS_USE && newEnable == RecordTaskRule.STATUS_USE) {
                    jsonObject.put("retValue", -2);
                } else {
                    modifyRecordPlanCommon(entity, recordPlan);
                    getRecordService().editRecordPlan(recordPlan);
                    updateRecordTaskRule(recordPlan);
                    if (newEnable == RecordTaskRule.STATUS_USE) {
                        getRecordAsyncService().changeRecordTaskRule(recordPlan.getId(), RecordTaskRule.STATUS_USE);
                    } else {
                        getRecordAsyncService().changeRecordTaskRule(recordPlan.getId(), RecordTaskRule.STATUS_STOP);
                    }
                    jsonObject.put("retValue", 1);
                }

                tResponse.setCode(Constants.CODE_SUC);
            }
        } catch (Exception e) {
            logger.error("ERROR", e);
        }
        tResponse.setJsonData(jsonObject.toJSONString());
        return tResponse;
    }

    private void modifyRecordPlanCommon(TRecordPlan entity, RecordPlan recordPlan) {
        recordPlan.setChannelId(entity.getChannelId());
        recordPlan.setColId(entity.getColId());
        recordPlan.setEnable(entity.getEnable());
        recordPlan.setNotifyType(entity.getNotifyType());
        recordPlan.setProjectWorkers(entity.getProjectWorkers());
        recordPlan.setFragmentOutput(entity.getFragmentOutput());
        recordPlan.setRepeatCode(entity.getRepeatCode());
        recordPlan.setStartDate(entity.getStartDate());
        recordPlan.setStopDate(entity.getStopDate());
        recordPlan.setStartDayTime(entity.getStartDayTime());
        recordPlan.setStopDayTime(entity.getStopDayTime());
        recordPlan.setPlanType(entity.getPlanType());
    }


    @Override
    public boolean deleteRecordPlan(long id, String opUser) {
        try {
            RecordPlan recordPlan = getRecordService().getRecordPlanById(id);
            if (recordPlan == null) {
                logger.warn("[deleteRecordPlan] no such id {}; op_usr {}", id, opUser);
                return false;
            }
            if (recordPlan.getEnable() == 1) {
                logger.warn("[deleteRecordPlan][running] id {}; op_usr {}", id, opUser);
                return false;
            }
            recordPlan.setStatus(0);
            getRecordService().editRecordPlan(recordPlan);
            getRecordAsyncService().addRecordTaskClearByPlan(recordPlan.getId(),false);
            logger.info("[deleteRecordPlan][suc] id {}; op_usr {}", id, opUser);
            return true;
        } catch (Exception e) {
            logger.error("ERROR", e);
            return false;
        }
    }

    @Override
    public TRecordPlan getRecordPlanById(long id) {
        try {
            RecordPlan recordPlan = getRecordService().getRecordPlanById(id);
            TRecordPlan tRecordPlan = getRecordService().transToTRecordPlan(recordPlan);
            return tRecordPlan;
        } catch (Exception e) {
            logger.error("ERROR", e);
            return new TRecordPlan();
        }
    }

    @Override
    public TRecordPlanPage findTRecordPlanPage(TPage page, TFilter filter) {
        IRecordService service = getRecordService();
        TRecordPlanPage dataPage = service.findPlanPage(page, filter);
        return dataPage;
    }

    @Override
    public TRecordPlanLibraryPage findTRecordPlanLibraryPage(TPage page, TFilter filter) {
        IRecordService service = getRecordService();
        TRecordPlanLibraryPage dataPage = service.findPlanLibraryPage(page, filter);
        return dataPage;
    }

    @Override
    public TRecordColSimplePage findTRecordColSimplePage(TPage page, TFilter filter) {
        IRecordService service = getRecordService();
        TRecordColSimplePage dataPage = service.findColSimplePage(page, filter);
        return dataPage;
    }

    @Override
    public TRecordChannelSimplePage findTRecordChannelSimplePage(TPage page, TFilter filter) {
        IRecordService service = getRecordService();
        TRecordChannelSimplePage dataPage = service.findChannelSimplePage(page, filter);
        return dataPage;
    }

    @Override
    public TResponse addRecordChannel(TRecordChannel entity) {
        TResponse tResponse = new TResponse();
        tResponse.setCode(Constants.CODE_ERROR);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("retValue", 0);
        try {
            RecordChannel recordChannel = new RecordChannel();
            recordChannel.setChannelCode(entity.getChannelCode());
            recordChannel.setChannelName(entity.getChannelName());
            recordChannel.setStatus(RecordChannel.STATUS_USE);
            recordChannel.setHasCaption(entity.getHasCaption() == 1 ? true : false);
            recordChannel.setOpUser(entity.getOpUser());
            recordChannel.setCreateTime(new Timestamp(System.currentTimeMillis()));
            long regId = getRecordService().saveRecordChannel(recordChannel);
            tResponse.setCode(Constants.CODE_SUC);
            jsonObject.put("retValue", regId);
        } catch (Exception e) {
            logger.error("ERROR", e);
        }
        tResponse.setJsonData(jsonObject.toJSONString());
        return tResponse;
    }

    @Override
    public TResponse editRecordChannel(TRecordChannel entity) {
        TResponse tResponse = new TResponse();
        tResponse.setCode(Constants.CODE_ERROR);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("retValue", 0);
        if (entity.getId() == 0) {
            jsonObject.put("retValue", 1);
            tResponse.setJsonData(jsonObject.toJSONString());
            return tResponse;
        }
        try {
            RecordChannel recordChannel = getRecordService().getRecordChannelById(entity.getId());
            if (recordChannel == null) {
                jsonObject.put("retValue", -1);
            } else {
                List<RecordCol> colList = getRecordColService().getRecordColListByChannelId(recordChannel.getId());
                recordChannel.setChannelCode(entity.getChannelCode());
                recordChannel.setChannelName(entity.getChannelName());
                recordChannel.setHasCaption(entity.getHasCaption() == 1 ? true : false);
                if (colList != null && colList.size() > 0) {
                    for (RecordCol col : colList) {
                        col.setChannelName(entity.getChannelName());
                        getRecordColService().update(col);
                    }
                }

                getRecordService().editRecordChannel(recordChannel);
                tResponse.setCode(Constants.CODE_SUC);
            }
        } catch (Exception e) {
            logger.error("ERROR", e);
        }
        tResponse.setJsonData(jsonObject.toJSONString());
        return tResponse;
    }

    @Override
    public boolean deleteRecordChannel(long id, String opUser) {
        try {
            RecordChannel recordChannel = getRecordService().getRecordChannelById(id);
            if (recordChannel == null) {
                logger.warn("[deleteRecordChannel] no such id {}; op_usr {}", id, opUser);
                return false;
            } else {
                IRecordService recordService = getRecordService();
                recordService.delRecordChannel(id);
                getRecordAsyncService().addRecordColClearByChannel(id);
                IRecordAsyncService recordAsyncService = getRecordAsyncService();
                recordAsyncService.unbindChannelSignalByChannelId(id);
                recordAsyncService.addRecordColClearByChannel(id);
                logger.info("[deleteRecordChannel][suc] id {}; op_usr {}", id, opUser);
                return true;
            }
        } catch (Exception e) {
            logger.error("ERROR", e);
            return false;
        }
    }


    @Override
    public TRecordChannelPage findTRecordChannelPage(TPage page, TFilter filter) {
        return getRecordService().findChannelPage(page, filter);
    }


    @Override
    public TResponse editRecordTask(TRecordTaskData entity) throws TException {
        TResponse tResponse = new TResponse();
        tResponse.setCode(Constants.CODE_ERROR);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("retValue", 0);
        if (entity.getId() == 0) {
            jsonObject.put("retValue", 1);
            tResponse.setJsonData(jsonObject.toJSONString());
            return tResponse;
        }
        try {
            RecordTask recordTask = getRecordService().getRecordTaskById(entity.getId());
            if (recordTask == null) {
                jsonObject.put("retValue", -1);
            } else {
                recordTask.setTaskStatus(entity.getTaskStatus());
                getRecordService().editRecordTask(recordTask);
                tResponse.setCode(Constants.CODE_SUC);
            }
        } catch (Exception e) {
            logger.error("ERROR", e);
        }
        tResponse.setJsonData(jsonObject.toJSONString());
        return tResponse;
    }

    @Override
    public TRecordTaskDataPage findTRecordTaskPage(TPage page, TFilter filter) throws TException {
        IRecordService service = getRecordService();
        TRecordTaskDataPage dataPage = service.findTaskDataPage(page, filter);
        return dataPage;
    }

    @Override
    public TRecordTaskLibraryPage findTRecordTaskLibraryPage(TPage page, TFilter filter) throws TException {
        IRecordService service = getRecordService();
        TRecordTaskLibraryPage dataPage = service.findTaskLibraryPage(page, filter);
        return dataPage;
    }


    @Override
    public TRecordSignalPage findTRecordSignalPage(TPage page, TFilter filter) {
        IRecordService service = getRecordService();
        TRecordSignalPage dataPage = service.findSignalPage(page, filter);
        return dataPage;
    }

    @Override
    public TResponse addRecordSignal(TRecordSignal entity) {
        TResponse tResponse = new TResponse();
        tResponse.setCode(Constants.CODE_ERROR);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("retValue", 0);
        try {
            RecordSignal recordSignal = new RecordSignal();
            recordSignal.setSignalName(entity.getSignalName());
            recordSignal.setSignalAddress(entity.getSignalAddress());
            recordSignal.setPriority(entity.getPriority());
            recordSignal.setServerCluster(entity.getServerCluster());
            recordSignal.setStatus(entity.getStatus());
            recordSignal.setOpUser(entity.getOpUser());
            recordSignal.setCreateTime(new Timestamp(System.currentTimeMillis()));
            long regId = getRecordService().saveRecordSignal(recordSignal);
            if (regId >= 0) {
                tResponse.setCode(Constants.CODE_SUC);
            } else {
                tResponse.setCode(Constants.CODE_ERROR_SIGNALNAME_EXIST);
            }

            jsonObject.put("retValue", regId);
        } catch (Exception e) {
            logger.error("ERROR", e);
        }
        tResponse.setJsonData(jsonObject.toJSONString());
        return tResponse;
    }

    @Override
    public TResponse deleteRecordSignal(long id, String opUser) {
        TResponse tResponse = new TResponse();
        tResponse.setCode(Constants.CODE_ERROR);
        try {

            IRecordService recordService = getRecordService();
            //查询信号是否关联
            List<RecordChannelSignal> recordChannelSignals = recordService.getRecordChannelSignalBySignalId(id);
            if (recordChannelSignals.size() > 0) {//有关联，返回错误
                logger.warn("[deleteRecordSignal] has related channel id={}; op_usr={}", id, opUser);
                tResponse.setMsg("删除失败：信号被频道关联 " + id);
                tResponse.setCode(Constants.CODE_ERROR_SIGNAL_RELATED);
                return tResponse;
            }

            RecordSignal recordSignal = recordService.getRecordSignalById(id);
            if (recordSignal == null) {
                logger.warn("[deleteRecordSignal] no such id {}; op_usr {}", id, opUser);
                tResponse.setMsg("删除失败：数据库没有找到 id" + id);
                tResponse.setCode(Constants.CODE_FAIL);
                return tResponse;
            } else {
                recordSignal.setStatus(-1);
                getRecordService().editRecordSignal(recordSignal);
                logger.info("[deleteRecordSignal][suc] id {}; op_usr {}", id, opUser);
                tResponse.setMsg("删除成功 " + id);
                tResponse.setCode(Constants.CODE_SUC);
                return tResponse;
            }
        } catch (Exception e) {
            logger.error("ERROR", e);
            tResponse.setMsg(e.toString());
            tResponse.setCode(Constants.CODE_FAIL);
            return tResponse;
        }


    }

    @Override
    public TResponse editRecordSignal(TRecordSignal entity) {
        TResponse tResponse = new TResponse();
        tResponse.setCode(Constants.CODE_ERROR);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("retValue", 0);
        if (entity.getId() == 0) {
            jsonObject.put("retValue", 1);
            tResponse.setJsonData(jsonObject.toJSONString());
            return tResponse;
        }
        try {
            IRecordService recordService = getRecordService();
            RecordSignal recordSignal = recordService.getRecordSignalById(entity.getId());
            if (recordSignal == null) {
                jsonObject.put("retValue", -1);
            } else {
                modifyRecordSignalCommon(entity, recordSignal);
                recordService.editRecordSignal(recordSignal);
                tResponse.setCode(Constants.CODE_SUC);
            }
        } catch (Exception e) {
            logger.error("ERROR", e);
        }
        tResponse.setJsonData(jsonObject.toJSONString());
        return tResponse;
    }

    private void modifyRecordSignalCommon(TRecordSignal entity, RecordSignal recordSignal) {
        recordSignal.setSignalName(entity.getSignalName());
        recordSignal.setSignalAddress(entity.getSignalAddress());
        recordSignal.setPriority(entity.getPriority());
        recordSignal.setServerCluster(entity.getServerCluster());
        recordSignal.setStatus(entity.getStatus());
    }


    @Override
    public TRecordSignal getRecordSignalById(long id) {
        try {
            RecordSignal recordSignal = getRecordService().getRecordSignalById(id);
            TRecordSignal tRecordSignal = getRecordService().transToTRecordSignal(recordSignal);
            return tRecordSignal;
        } catch (Exception e) {
            logger.error("ERROR", e);
            return new TRecordSignal();
        }
    }

    @Override
    public TRecordChannelSignalPage findTRecordChannelSignalPage(TPage page, TFilter filter) {
        IRecordService service = getRecordService();
        TRecordChannelSignalPage dataPage = service.findChannelSignalPage(page, filter);
        return dataPage;
    }

    @Override
    public TResponse addRecordChannelSignal(TRecordChannelSignal entity) {
        TResponse tResponse = new TResponse();
        tResponse.setCode(Constants.CODE_ERROR);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("retValue", 0);
        try {
            RecordChannelSignal recordChannelSignal = new RecordChannelSignal();
            modifyRecordChannelSignalCommon(entity, recordChannelSignal);
            recordChannelSignal.setOpUser(entity.getOpUser());
            recordChannelSignal.setCreateTime(new Timestamp(System.currentTimeMillis()));
            recordChannelSignal.setStatus(0); //默认关闭
            long regId = getRecordService().saveRecordChannelSignal(recordChannelSignal);
            if (regId >= 0) {
                tResponse.setCode(Constants.CODE_SUC);
            } else {
                tResponse.setCode(Constants.CODE_ERROR_SIGNALNAME_EXIST);
            }
            jsonObject.put("retValue", regId);
        } catch (Exception e) {
            logger.error("ERROR", e);
        }
        tResponse.setJsonData(jsonObject.toJSONString());
        return tResponse;
    }

    @Override
    public boolean deleteRecordChannelSignal(long id, String opUser) {
        return getRecordService().delRecordChannelSignal(id);
    }

    @Override
    public TResponse editRecordChannelSignal(TRecordChannelSignal entity) {
        TResponse tResponse = new TResponse();
        tResponse.setCode(Constants.CODE_ERROR);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("retValue", 0);
        if (entity.getId() == 0) {
            jsonObject.put("retValue", 1);
            tResponse.setJsonData(jsonObject.toJSONString());
            return tResponse;
        }
        try {
            IRecordService recordService = getRecordService();
            RecordChannelSignal recordChannelSignal = recordService.getRecordChannelSignalById(entity.getId());
            if (recordChannelSignal == null) {
                jsonObject.put("retValue", -1);
            } else {
                modifyRecordChannelSignalCommon(entity, recordChannelSignal);
                recordService.editRecordChannelSignal(recordChannelSignal);
                tResponse.setCode(Constants.CODE_SUC);
            }
        } catch (Exception e) {
            logger.error("ERROR", e);
        }
        tResponse.setJsonData(jsonObject.toJSONString());
        return tResponse;
    }

    private void modifyRecordChannelSignalCommon(TRecordChannelSignal entity, RecordChannelSignal recordChannelSignal) {
        recordChannelSignal.setSignalId(entity.getSignalId());
        recordChannelSignal.setChannelId(entity.getChannelId());
        recordChannelSignal.setServerIp("0.0.0.0");
    }


    @Override
    public TRecordChannelSignal getRecordChannelSignalById(long recordChannelSignalId) {
        try {
            TRecordChannelSignal tRecordChannelSignal = getRecordService().transToTRecordChannelSignal(recordChannelSignalId);
            return tRecordChannelSignal;
        } catch (Exception e) {
            logger.error("ERROR", e);
            return new TRecordChannelSignal();
        }
    }

    @Override
    public TResponse startRecordChannelSignal(long id, String opUser) {
        //获取当前数据
        TResponse tResponse = new TResponse();
        tResponse.setCode(Constants.CODE_ERROR);
        JSONObject jsonObject = new JSONObject();

        IRecordService recordService = getRecordService();
        TRecordChannelSignal tRecordChannelSignal = recordService.getTRecordChannelSignal(id);
        //获取可用收录数
        int serverAvailableIncluding = recordService.getServerAvailableIncluding(tRecordChannelSignal.getId(),tRecordChannelSignal.getServerIp());
        if (serverAvailableIncluding <= 0) {
            jsonObject.put("retValue", "服务器可用收录数不足");
            logger.error("startRecordChannelSignal[serverAvailableIncluding={},not enough]", serverAvailableIncluding);
            tResponse.setJsonData(jsonObject.toJSONString());
            return tResponse;
        }

        try {
            if (tRecordChannelSignal == null) {
                jsonObject.put("retValue", "tRecordChannelSignal 为空,数据库没有找到");
                tResponse.setJsonData(jsonObject.toJSONString());
                logger.error("startRecordChannelSignal[tRecordChannelSignal == null][id=" + id + "]");
                return tResponse;
            }
            int channelSignalStatus = tRecordChannelSignal.getStatus();
            if (channelSignalStatus == 1) {
                jsonObject.put("retValue", "流状态" + tRecordChannelSignal.getSignalAddress() + "已经启动: " + channelSignalStatus);
                logger.error("startRecordChannelSignal[流状态" + tRecordChannelSignal.getSignalAddress() + "已经启动: " + channelSignalStatus + "]");
                tResponse.setJsonData(jsonObject.toJSONString());
                return tResponse;
            }
            String ip = tRecordChannelSignal.getServerIp();
            if (ip == null) {
                jsonObject.put("retValue", "ip 地址为空");
                logger.error("startRecordChannelSignal[ip 地址为空]");
                tResponse.setJsonData(jsonObject.toJSONString());
                return tResponse;
            }
            jsonObject = ApiRecordNotifyUtil.notifyStart(tRecordChannelSignal.getId(), ip, tRecordChannelSignal.getSignalAddress(), tRecordChannelSignal.getChannelCode());
            logger.info("startRecordChannelSignal[id=" + id + "][address=" + tRecordChannelSignal.getSignalAddress() + "]" + "][result=" + jsonObject.toJSONString() + "]");
            if (Constants.CODE_SUC.equals(jsonObject.getString("code"))) {
                tResponse.setCode(Constants.CODE_SUC);
                recordService.updateRecordChannelSignalStatus(tRecordChannelSignal.getId(), 1);
            }
            tResponse.setJsonData(jsonObject.toJSONString());
        } catch (Exception e) {
            jsonObject.put("retValue", e.toString());
            tResponse.setJsonData(jsonObject.toJSONString());
            logger.error("startRecordChannelSignal[exception]{}", e);
        }
        return tResponse;
    }

    @Override
    public TResponse stopRecordChannelSignal(long id, String opUser) {
        //获取当前数据
        TResponse tResponse = new TResponse();
        tResponse.setCode(Constants.CODE_ERROR);
        JSONObject jsonObject = new JSONObject();
        IRecordService recordService = getRecordService();
        try {
            TRecordChannelSignal tRecordChannelSignal = recordService.getTRecordChannelSignal(id);
            if( tRecordChannelSignal == null){
                jsonObject.put("retValue", "tRecordChannelSignal == null");
                tResponse.setJsonData(jsonObject.toJSONString());
                return tResponse;
            }
            int channelSignalStatus = tRecordChannelSignal.getStatus();
            if (channelSignalStatus == 0) { //是否已经关闭
                jsonObject.put("retValue", "流状态" + tRecordChannelSignal.getSignalAddress() + "已经关闭: " + channelSignalStatus);
                tResponse.setJsonData(jsonObject.toJSONString());
                logger.error("startRecordChannelSignal[流状态" + tRecordChannelSignal.getSignalAddress() + "已经关闭: " + channelSignalStatus + "]");
                return tResponse;
            }
            String ip = tRecordChannelSignal.getServerIp();
            if (ip == null) {
                jsonObject.put("retValue", "ip 地址为空!");
                tResponse.setJsonData(jsonObject.toJSONString());
                return tResponse;
            }
            jsonObject = ApiRecordNotifyUtil.notifyStop(tRecordChannelSignal.getId(), ip);
            logger.info("stopRecordChannelSignal[id=" + id + "][address=" + tRecordChannelSignal.getSignalAddress() + "]" + "][result=" + jsonObject.toJSONString() + "]");
            if (Constants.CODE_SUC.equals(jsonObject.getString("code"))) {
                tResponse.setCode(Constants.CODE_SUC);
                //修改状态
                recordService.updateRecordChannelSignalStatus(tRecordChannelSignal.getId(), 0);
            }
            tResponse.setJsonData(jsonObject.toJSONString());
        } catch (Exception e) {
            jsonObject.put("retValue", e.toString());
            tResponse.setJsonData(jsonObject.toJSONString());
            logger.error("stopRecordChannelSignal[exception]{}", e);
        }
        return tResponse;
    }

    @Override
    public TRecordChannelSignalTablePage findTRecordChannelSignalTablePage(TPage page, TFilter filter) {
        return getRecordService().findRecordChannelSignalTablePage(page, filter);
    }

    @Override
    public TResponse updateRecordVideoStatus(long signalId, long taskId, long videoId, int videoStatus) {

        TResponse tResponse = new TResponse();
        tResponse.setCode(Constants.CODE_ERROR);

        try {
            RecordVideo recordVideo = getRecordService().updateRecordVideoStatus(signalId, taskId, videoId, videoStatus);
            if (recordVideo != null) {
                tResponse.setCode(Constants.CODE_SUC);
                tResponse.setMsg(recordVideo.getSignalId() + "update success");

            } else {
                tResponse.setCode(Constants.CODE_ERROR);
                tResponse.setMsg("signal not found");
            }
            return tResponse;
        } catch (Exception e) {
            tResponse.setMsg("exception:" + e);
            logger.error("updateRecordVideoStatus[exception]{}", e);
            return tResponse;
        }
    }

    @Override
    public TResponse updateRecordTaskStatus(long taskId, int videoStatus) {

        TResponse tResponse = new TResponse();
        tResponse.setCode(Constants.CODE_ERROR);

        try {
            RecordTask recordTask = getRecordService().updateRecordTaskStatus( taskId,  videoStatus);
            if (recordTask != null) {
                tResponse.setCode(Constants.CODE_SUC);
                tResponse.setMsg(recordTask.getId() + "update success");

            } else {
                tResponse.setCode(Constants.CODE_ERROR);
                tResponse.setMsg("task not found");
            }
            return tResponse;
        } catch (Exception e) {
            tResponse.setMsg("exception:" + e);
            logger.error("updateRecordTaskStatus[exception]{}", e);
            return tResponse;
        }

    }
}
